package tcpsession

import (
	log "github.com/sirupsen/logrus"
	"sync"
	"usbipproxy/domain"
	"usbipproxy/domain/vo"
)

type TcpSessionMgr struct {
	rwLock      sync.RWMutex
	dispatchMap map[string]*domain.DispatchClient
	connMap     map[int64]*domain.DispatchClient
}

func (mgr *TcpSessionMgr) AddDispatch(did string, cli *domain.DispatchClient) {
	mgr.rwLock.Lock()
	defer mgr.rwLock.Unlock()

	mgr.dispatchMap[did] = cli
	log.Infof("add new client for did %s", did)
}

func (mgr *TcpSessionMgr) AddConn(connId int64, cli *domain.DispatchClient) {
	mgr.rwLock.Lock()
	defer mgr.rwLock.Unlock()

	mgr.connMap[connId] = cli
	log.Infof("add new client for connId %v", connId)
}

func (mgr *TcpSessionMgr) DelByConnId(connId int64) {
	mgr.rwLock.Lock()
	defer mgr.rwLock.Unlock()

	cli := mgr.connMap[connId]

	delete(mgr.connMap, connId)
	if cli != nil {
		delete(mgr.dispatchMap, cli.GetDid())
		log.Infof("del a dispatch client for did %s", cli.GetDid())
	}
	log.Infof("del a dispatch client for connId %v", connId)
}

func (mgr *TcpSessionMgr) GetByConnId(connId int64) *domain.DispatchClient {
	mgr.rwLock.RLock()
	defer mgr.rwLock.RUnlock()

	return mgr.connMap[connId]
}

func (mgr *TcpSessionMgr) GetByDid(did string) *domain.DispatchClient {
	mgr.rwLock.RLock()
	defer mgr.rwLock.RUnlock()

	return mgr.dispatchMap[did]
}

func (mgr *TcpSessionMgr) GetAllList() []*vo.DispatchInfo {
	mgr.rwLock.RLock()
	defer mgr.rwLock.RUnlock()

	var ret []*vo.DispatchInfo
	for _, item := range mgr.dispatchMap {
		ret = append(ret, &vo.DispatchInfo{
			DispatchId: item.GetDid(),
			ConnId:     item.GetConnId(),
		})
	}

	return ret
}

func NewTcpSessionMgr() TcpSessionMgrRepo {
	return &TcpSessionMgr{
		connMap:     make(map[int64]*domain.DispatchClient),
		dispatchMap: make(map[string]*domain.DispatchClient),
	}
}
